package com.ibm.st.talent.update.profile.status;

/*
 * Licensed Materials - Property of IBM
 *
 * L-KBIM-82KJL8
 *
 * (C) Copyright IBM Corp. 2006, 2010. All rights reserved.
 *
 * US Government Users Restricted Rights- Use, duplication or
 * disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
 */

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.eclipse.jface.dialogs.IMessageProvider;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.FontMetrics;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Monitor;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.ibm.collaboration.realtime.buddylist.BuddyList;
import com.ibm.collaboration.realtime.buddylist.BuddyListServiceUtil;
import com.ibm.collaboration.realtime.people.Person;

/**
 * Shows how to add a basic QuickFindWidget to a Dialog
 */

public class ProfileUpdateDialog extends TitleAreaDialog {

	private Text text;	
	private String userId = "";
	private String password = "";

	public ProfileUpdateDialog(Shell shell) {
		super(shell);
	}

	protected void configureShell(Shell shell) {
		super.configureShell(shell);
		shell.setText("Your New Status");
		
	}

	protected Control createDialogArea(Composite parent) {
		
		this.setMessage("Please input your new status in below input control, " +
				"then it will be \n updated to Lotus Connection Profile on W3.", IMessageProvider.INFORMATION);
		
		Composite c = new Composite(parent, SWT.CENTER);
		
		FormLayout layout = new FormLayout ();
		layout.marginWidth = layout.marginHeight = 20;
		c.setLayout(layout);
		
		text = new Text (c, SWT.MULTI | SWT.BORDER | SWT.WRAP);
		
		int columns = 75;
		int lines = 4;
		GC gc = new GC (text);
		FontMetrics fm = gc.getFontMetrics ();
		

		int width = columns * fm.getAverageCharWidth ();
		int height = lines * text.getLineHeight();
		
		FormData data = new FormData (width, height);
		text.setLayoutData (data);
				
		text.setFocus();
		return c;
	}

	@Override
	protected void okPressed() {
		String newStatus = this.text.getText().trim();
		if(newStatus.length() > 0){
			sendStatus(newStatus);
		}else{
			System.out.println("No status input.");
		}
		super.okPressed();
	}

	private void sendStatus(String newStatus) {
		
		HttpClient client = newClient();		
		PutMethod method = newMethod(newStatus, statusUrl());
		
		try {
			// Execute the method.
			int statusCode = client.executeMethod(method);
			System.out.println(statusCode);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: " + method.getStatusLine());
				
				if(statusCode == HttpStatus.SC_UNAUTHORIZED){					
					AuthenticationDialog authDialog = new AuthenticationDialog(getShell());					
					
					if(authDialog.open() == Window.OK){
						password = authDialog.getPwd();
						
						client = newClient();
						method = newMethod(newStatus, statusUrl());
						statusCode = client.executeMethod(method);
						
						if (statusCode != HttpStatus.SC_OK) {
							System.err.println("Method failed: " + method.getStatusLine());
							MessageDialog.openError(null, "Update status failed !",
									"Update status failed: " + method.getStatusLine());
						}else{
							updateDisplayStatus(newStatus);
						}
					}
				}
			}else{
				// Read the response body.
				byte[] responseBody = method.getResponseBody();				
				updateDisplayStatus(newStatus);
			}

		} catch (HttpException e) {
			System.err.println("Fatal protocol violation: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Fatal transport error: " + e.getMessage());
			e.printStackTrace();
			
		} finally {
			// Release the connection.
			method.releaseConnection();
		}
	}

	private void updateDisplayStatus(String newStatus) {
		BuddyList list = BuddyListServiceUtil.getBuddyListService().getBuddyList();
		Person[] persons = list.getAllPersons(true);
		
		for(Person person : persons){
			if(this.userId.equalsIgnoreCase(person.getContactId())){
				String displayName = person.getDisplayName();
				int indexOfStatus = displayName.indexOf(" - [");
				String trueName = indexOfStatus > 0 ? displayName.substring(0, indexOfStatus) : displayName;
				person.setDisplayName(trueName + " - ["+ newStatus +"]");
			}
			
		}
		
	}

	private String statusUrl() {
		String user = userId.replace("@", "%40");
		return "https://w3.ibm.com/connections/profiles/atom/mv/theboard/entry/status.do?email="+user;
	}

	private PutMethod newMethod(String newStatus, String url) {
		PutMethod method = new PutMethod(url);
		method.setDoAuthentication(true);
		method.addRequestHeader("Content-Type", "application/atom+xml; charset=UTF-8");		
		try {
			method.setRequestEntity(new StringRequestEntity(atomEntry(newStatus), "application/atom+xml", "UTF-8"));
		} catch (UnsupportedEncodingException e) {			
			e.printStackTrace();
		}
		return method;
	}

	private HttpClient newClient() {
		HttpClient client = new HttpClient();
		client.getState().setCredentials(
				new AuthScope(null, 443, null),
				new UsernamePasswordCredentials(userId, password));

		return client;
	}

	private String atomEntry(String newStatus) {
		return atomEntryTemplate().replace("STATUS", newStatus);
	}
	
	private String atomEntryTemplate(){
		String template = 
			"<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
			"<entry xmlns=\"http://www.w3.org/2005/Atom\">" +
				"<title type=\"text\">STATUS</title>" +
				"<category term=\"entry\" scheme=\"http://www.ibm.com/xmlns/prod/sn/type\"/>" +
				"<category term=\"status\" scheme=\"http://www.ibm.com/xmlns/prod/sn/message-type\"/>" +
				"<summary type=\"text\">STATUS</summary>" +
				"<content type=\"text\">STATUS</content>" +
			"</entry>";
		
		return template;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String pwd) {
		this.password = pwd;
		
	}

	public void setUserid(String userid2) {
		this.userId = userid2;
		
	}
	
	protected void initializeBounds() {
		super.initializeBounds();
		Shell shell = this.getShell();
		Monitor primary = shell.getMonitor();
		Rectangle bounds = primary.getBounds();
		Rectangle rect = shell.getBounds();
		int x = bounds.x + (bounds.width - rect.width) / 2;
		int y = bounds.y + (bounds.height - rect.height) / 2;
		shell.setLocation(x, y);
	}
	
}
